package com.hrb.douban.fragment;


import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.hrb.commonsdk.okhttp.listener.DisposeDataListener;
import com.hrb.commonsdk.okhttp.request.RequestParams;
import com.hrb.douban.CustomApplication;
import com.hrb.douban.OnItemClickListener;
import com.hrb.douban.R;
import com.hrb.douban.activtity.FilmDetailsActivity;
import com.hrb.douban.adapter.ComingAdapter;
import com.hrb.douban.constant.ConstantCode;
import com.hrb.douban.constant.HttpConstants;
import com.hrb.douban.mview.LoadingView;
import com.hrb.douban.network.RequestCenter;
import com.hrb.douban.record.Comingrecord;
import com.hrb.douban.record.SubjectsBean;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.footer.ClassicsFooter;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;

/**
 * A simple {@link Fragment} subclass.
 */
public class TopFragment extends Fragment {

    @BindView(R.id.top_recycler_view)
    RecyclerView recyclerView;
    @BindView(R.id.top_swipe_refresh)
    SmartRefreshLayout swipeRefresh;
    @BindView(R.id.loading_view)
    LoadingView loadingView;
    private Unbinder unbinder;
    private int scrollY = 0;
    private ComingAdapter adapter;
    private int start = 0;
    private int lastPosition = 0;
    private int lastOffset = 0;

    public TopFragment() {
        // Required empty public constructor
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        RequestParams params = new RequestParams();
        params.put("city", "哈尔滨");
        params.put("start", start + "");
        params.put("count", "20");
        requestData(params);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_top, container, false);
        unbinder = ButterKnife.bind(this, view);
        GridLayoutManager gridLayoutManager = new GridLayoutManager(getContext(), 2);
        recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
            }

            @Override
            public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                //Log.d("messageDY : ", dy + "");
                scrollY += dy;
                if (scrollY > 100) {
                    //thirdTitleBar.setVisibility(View.GONE);
                } else {
                    //thirdTitleBar.setVisibility(View.VISIBLE);
                }
                //Log.d("message : ", scrollY + "");
            }
        });
        recyclerView.setLayoutManager(gridLayoutManager);
        /**
         * 记录recyclerView 在视图的位置添加滚动事件
         */
        recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                if (recyclerView.getLayoutManager() != null) {
                    getPositionAndOffset();
                }
            }
        });
        //关闭下拉
        swipeRefresh.setEnableRefresh(false);
        //底部信息
        swipeRefresh.setRefreshFooter(new ClassicsFooter(CustomApplication.getContext()));
        swipeRefresh.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                RequestParams params = new RequestParams();
                params.put("city", "哈尔滨");
                params.put("start", start + "");
                params.put("count", "20");
                requestData(params);
                //requestData(null);
                swipeRefresh.finishLoadMore(2000);
            }
        });
        return view;
    }

    private void requestData(RequestParams params) {
        RequestCenter.getRequest(HttpConstants.TOP, params, Comingrecord.class, new DisposeDataListener() {
            @Override
            public void onSuccess(Object responseObj) {
                Comingrecord comingrecord = (Comingrecord) responseObj;

                if (responseObj != null && comingrecord.getCount() > 0) {
                    if (start == 0) {
                        adapter = new ComingAdapter(comingrecord.getSubjects());
                    } else {
                        adapter.add(comingrecord.getSubjects());
                    }
                    start += comingrecord.getSubjects().size();
                    View footer = (View) LayoutInflater.from(getActivity()).inflate(R.layout.coming_footer, recyclerView, false);
                    TextView textView = footer.findViewById(R.id.coming_bottom_message);
                    if (start == comingrecord.getTotal()) {
                        textView.setText("没有更多了");
                        swipeRefresh.setNoMoreData(true);
                    } else {
                        textView.setText("加载更多");
                    }
                    adapter.setFooterView(footer);
                    adapter.setOnItemClickListener(new OnItemClickListener() {
                        SubjectsBean subjectsBean;

                        @Override
                        public void onItemClick(View view, int position) {
                            subjectsBean = adapter.getSubjects().get(position);
                            Intent intent = new Intent(getActivity(), FilmDetailsActivity.class);
                            intent.putExtra("id", subjectsBean.getId());
                            getActivity().startActivityForResult(intent, ConstantCode.requestCode);
                        }

                        @Override
                        public void onCategoryClick(View view, String category) {

                        }
                    });
                    recyclerView.setAdapter(adapter);
                    loadingView.setVisibility(View.GONE);
                    scrollToPosition();
                }
            }

            @Override
            public void onFailure(Object reasonObj) {

            }
        });
    }

    /**
     * 让RecyclerView滚动到指定位置
     */
    private void scrollToPosition() {
        if (recyclerView.getLayoutManager() != null && lastPosition >= 0) {
            ((LinearLayoutManager) recyclerView.getLayoutManager()).scrollToPositionWithOffset(lastPosition, lastOffset);
        }
    }

    /**
     * 记录RecyclerView当前位置
     */
    private void getPositionAndOffset() {
        LinearLayoutManager layoutManager = (LinearLayoutManager) recyclerView.getLayoutManager();
        //获取可视的第一个view
        View topView = layoutManager.getChildAt(0);
        if (topView != null) {
            //获取与该view的顶部的偏移量
            lastOffset = topView.getTop();
            //得到该View的数组位置
            lastPosition = layoutManager.getPosition(topView);
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }
}
